﻿using System.Collections.Generic;
using UnityEngine;

public class Pool
{
    # region 单例
    private static Pool instance;

    public static Pool Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Pool();
            }
            return instance;
        }
    }

    #endregion

    //容器
    private Dictionary<GameObject, List<GameObject>> pool = new Dictionary<GameObject, List<GameObject>>();

    //创建
    /// <summary>
    /// 通过换缓存池创建物体
    /// </summary>
    /// <param name="path">预制体在resources文件夹下路径</param>
    public GameObject Instantiate(GameObject path)
    {
        if (!pool.ContainsKey(path))//保证有path对应的list
        {
            pool.Add(path, new List<GameObject>());
        }
        //看下池子里有没有可以用的游戏物体
        List<GameObject> list = pool[path];
        for (int i = 0; i < list.Count; i++)//有就激活
        {
            if (!list[i].activeSelf)
            {
                list[i].SetActive(true);
                return list[i];
            }
        }
        //没有就实例化一个放入池子
        // GameObject perfab = Resources.Load(path) as GameObject;
        GameObject perfab = path;
        GameObject go = Object.Instantiate(perfab);//实例化
        pool[path].Add(go);
        return go;
    }

    //回收
    public void Destory(GameObject go, float time = 0)
    {
        go.SetActive(false);
    }
}